/******************************************************************************
 * Copyright (C) 2017 Chengdu Dlhd information industry co. LTD.
 * All Rights Reserved.
 * 本软件为成都顶联互动信息产业有限公司开发研制。未经本公司正式书面同意，其他任何个人、团体不得使用、复制、修改或发布本软件.
 *****************************************************************************/
package net.dgg.dggcloud.service.jrcrm.service.predict;

import net.dgg.dggcloud.core.idwork.KeyWorker;
import net.dgg.dggcloud.core.util.DateUtil;
import net.dgg.dggcloud.core.util.StringUtils;
import net.dgg.dggcloud.service.common.base.SessionManager;
import net.dgg.dggcloud.service.common.base.service.BaseService;
import net.dgg.dggcloud.service.common.exception.BizException;
import net.dgg.dggcloud.service.jrcrm.dao.predict.OrganizationMonthGoalDao;
import net.dgg.dggcloud.service.jrcrm.dao.predict.UserTomorrowGoalDao;
import net.dgg.dggcloud.service.jrcrm.entity.predict.OrganizationMonthGoal;
import net.dgg.dggcloud.service.jrcrm.entity.predict.UserTomorrowGoal;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.net.BindException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: UserTomorrowGoalService
 * @Description:
 * @author 钟鑫
 * @date 2017年11月21日 10:40:37
 */
@Service
public class UserTomorrowGoalService extends BaseService {
    @Autowired
    private UserTomorrowGoalDao userTomorrowGoalDao;

    @Autowired
    private KeyWorker keyWorker;


    /**
     * 根据参数查询结果,没有关联表
     * @param paramsMap 参数
     * @return 结果集合
     */
    public List<Map> queryUserTomorrowGoalByMap(Map paramsMap){
        List<Map> resultMapList =  userTomorrowGoalDao.queryUserTomorrowGoalByMap(paramsMap);

        // 将业绩相关数据从  分->元
        if (CollectionUtils.isNotEmpty(resultMapList)){
            for (Map resutltMap : resultMapList){
                resutltMap.put("achievementMortgageCount",new BigDecimal(resutltMap.get("achievementMortgageCount").toString()).divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP).toString());
                resutltMap.put("achievementCreditLoanCount",new BigDecimal(resutltMap.get("achievementCreditLoanCount").toString()).divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP).toString());
                resutltMap.put("achievementCapitalBusCount",new BigDecimal(resutltMap.get("achievementCapitalBusCount").toString()).divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP).toString());
                resutltMap.put("achievementTotalCount",new BigDecimal(resutltMap.get("achievementTotalCount").toString()).divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP).toString());
            }

        }
        return resultMapList;
    }

    /**
     * 根据部门查询部门下用户的明日预估数据，用户表为主表进行关联查询
     * @param paramsMap 参数map
     * @return 结果集合
     */
    public List<Map> queryOrgUserTomorrowGoalByMap(Map paramsMap) {
        List<Map> resultMapList =  userTomorrowGoalDao.queryOrgUserTomorrowGoalByMap(paramsMap);

        // 将业绩相关数据从  分->元
        if (CollectionUtils.isNotEmpty(resultMapList)){
            for (Map resutltMap : resultMapList){
                // 因为都是必填项，所以只要一个不为空的话，说明其它的都不为空
                if (null != resutltMap.get("achievementMortgageCount")){
                    resutltMap.put("achievementMortgageCount",new BigDecimal(resutltMap.get("achievementMortgageCount").toString()).divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP).toString());
                    resutltMap.put("achievementCreditLoanCount",new BigDecimal(resutltMap.get("achievementCreditLoanCount").toString()).divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP).toString());
                    resutltMap.put("achievementCapitalBusCount",new BigDecimal(resutltMap.get("achievementCapitalBusCount").toString()).divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP).toString());
                    resutltMap.put("achievementTotalCount",new BigDecimal(resutltMap.get("achievementTotalCount").toString()).divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP).toString());
                }
            }

        }
        return resultMapList;
    }

    /**
     * 根据参数创建或修改数据
     * @param paramsMap 参数
     */
    public void saveOrUpdateUserTomorrowGoal(Map paramsMap){
        UserTomorrowGoal userTomorrowGoal = new UserTomorrowGoal();
        String validateMsg = validateParameter(paramsMap,userTomorrowGoal);
        if (StringUtils.isNotBlank(validateMsg)){
            throw new BizException(validateMsg,BizException.DEFAULT_CODE);
        }
        String idStr = paramsMap.get("id").toString();

        // 如果是修改
        if (StringUtils.isNotBlank(idStr)){
            Long id = Long.parseLong(idStr);
            UserTomorrowGoal oldUserTomorrow = repository.get(UserTomorrowGoal.class,id);
            if (null == oldUserTomorrow){
                throw  new BizException("当前预估不存在，无法修改！",BizException.DEFAULT_CODE);
            }
            if (oldUserTomorrow.getModifyCount() >= 1){
                throw  new BizException("当前预估已被修改过一次，无法继续修改！",BizException.DEFAULT_CODE);
            }
            BeanUtils.copyProperties(userTomorrowGoal,oldUserTomorrow,"id","createTime","createrId","createrOrgId","createrName","modifyCount");
            oldUserTomorrow.setModifyCount(oldUserTomorrow.getModifyCount()+1);
            oldUserTomorrow.setUpdaterUser(SessionManager.getCurrentUser());
            repository.saveOrUpdate(oldUserTomorrow);
        } else {
            userTomorrowGoal.setCreateUser(SessionManager.getCurrentUser());
            userTomorrowGoal.setUpdaterUser(SessionManager.getCurrentUser());
            userTomorrowGoal.setModifyCount(0);
            userTomorrowGoal.setId(keyWorker.nextId());
            repository.save(userTomorrowGoal);
        }

    }

    /**
     * 验证传入的参数
     * @param paramsMap 参数map
     * @param userTomorrowGoal 实体对象
     * @return 验证结果
     */
    private String validateParameter(Map paramsMap, UserTomorrowGoal userTomorrowGoal) {
        StringBuilder sb = new StringBuilder();
        // 用户
        String userId = paramsMap.get("userId").toString();
        String userName = paramsMap.get("userName").toString();
        if (StringUtils.isBlank(userId)){
            sb.append("用户不能为空！");
        }
        // 用户部门
        String userOrgId = paramsMap.get("userOrgId").toString();
        String userOrgName = paramsMap.get("userOrgName").toString();
        if (StringUtils.isBlank(userOrgId)){
            sb.append("用户部门不能为空！");
        }
        // 电话量
        String phoneCount = paramsMap.get("phoneCount").toString();
        // 意向客户
        String intentionCustomerCount = paramsMap.get("intentionCustomerCount").toString();
        // 上门量
        String visitCount = paramsMap.get("visitCount").toString();
        if (StringUtils.isBlank(phoneCount) || StringUtils.isBlank(intentionCustomerCount) || StringUtils.isBlank(visitCount)){
            sb.append("电话量、意向客户、上门量不能为空！");
        }
        // 签单量-抵押量
        String signBillMortgageCount = paramsMap.get("signBillMortgageCount").toString();
        // 签单量-信贷量
        String signBillCreditLoanCount = paramsMap.get("signBillCreditLoanCount").toString();
        // 签单量-资金业务量
        String signBillCapitalBusCount = paramsMap.get("signBillCapitalBusCount").toString();
        // 签单量-合计量
        String signBillTotalCount = paramsMap.get("signBillTotalCount").toString();
        if (StringUtils.isBlank(signBillMortgageCount) || StringUtils.isBlank(signBillCreditLoanCount) || StringUtils.isBlank(signBillCapitalBusCount) || StringUtils.isBlank(signBillTotalCount)){
            sb.append("签单量-抵押、签单量-信贷、签单量-资金业务、签单量-合计不能为空！");
        }
        // 业绩-抵押量
        String achievementMortgageCount = paramsMap.get("achievementMortgageCount").toString();
        // 业绩-信贷量
        String achievementCreditLoanCount = paramsMap.get("achievementCreditLoanCount").toString();
        // 业绩-资金业务量
        String achievementCapitalBusCount = paramsMap.get("achievementCapitalBusCount").toString();
        // 业绩-合计
        String achievementTotalCount = paramsMap.get("achievementTotalCount").toString();
        if (StringUtils.isBlank(achievementMortgageCount) || StringUtils.isBlank(achievementCreditLoanCount) || StringUtils.isBlank(achievementCapitalBusCount) || StringUtils.isBlank(achievementTotalCount)){
            sb.append("业绩-抵押、业绩-信贷、业绩-资金业务、业绩-合计不能为空！");
        }
        // 有效日期
        String validDate = paramsMap.get("validDate").toString();
        if (StringUtils.isBlank(validDate)){
            sb.append("有效日期不能为空！");
        }
        String validateMsg = sb.toString();
        if (StringUtils.isBlank(validateMsg)){
            userTomorrowGoal.setUserId(Long.parseLong(userId));
            userTomorrowGoal.setUserName(userName);
            userTomorrowGoal.setUserOrgId(Long.parseLong(userOrgId));
            userTomorrowGoal.setUserOrgName(userOrgName);
            userTomorrowGoal.setPhoneCount(Integer.parseInt(phoneCount));
            userTomorrowGoal.setIntentionCustomerCount(Integer.parseInt(intentionCustomerCount));
            userTomorrowGoal.setVisitCount(Integer.parseInt(visitCount));
            userTomorrowGoal.setSignBillMortgageCount(Integer.parseInt(signBillMortgageCount));
            userTomorrowGoal.setSignBillCreditLoanCount(Integer.parseInt(signBillCreditLoanCount));
            userTomorrowGoal.setSignBillCapitalBusCount(Integer.parseInt(signBillCapitalBusCount));
            userTomorrowGoal.setSignBillTotalCount(Integer.parseInt(signBillTotalCount));
            userTomorrowGoal.setAchievementMortgageCount(new BigDecimal(achievementMortgageCount).multiply(new BigDecimal(100)).longValue());
            userTomorrowGoal.setAchievementCreditLoanCount(new BigDecimal(achievementCreditLoanCount).multiply(new BigDecimal(100)).longValue());
            userTomorrowGoal.setAchievementCapitalBusCount(new BigDecimal(achievementCapitalBusCount).multiply(new BigDecimal(100)).longValue());
            userTomorrowGoal.setAchievementTotalCount(new BigDecimal(achievementTotalCount).multiply(new BigDecimal(100)).longValue());
            userTomorrowGoal.setValidDate(DateUtil.stringToDate(validDate,"yyyy-MM-dd"));
        }
        return validateMsg;
    }

    /**
     * 根据参数统计工作台今日预估数据
     * @param tomorrowGoalMap 参数map
     * @return 统计结果
     */
    public Integer sumWorkbenchTodayGoalByMap(Map tomorrowGoalMap) {
        if (null == tomorrowGoalMap.get("column")){
            throw new BizException("需要统计的列不能为空！",BizException.DEFAULT_CODE);
        }
        return userTomorrowGoalDao.sumWorkbenchTodayGoalByMap(tomorrowGoalMap);
    }
}
